#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import time
import os

from Ump import utils, defs
from Ump.common import exception
from Ump.common import config
from Ump.common import log

from Ump.objs.manager_base import Manager
from Ump.objs.alert.api import AlertApi
from Ump.objs.session_wrapper import enable_log_and_session, _sw
from Ump.objs.db import models


LOG = log.get_log('Ump.objs.callhome.manager')
alert_api = AlertApi()


def no_unicode(x):
    if isinstance(x, unicode):
        return x.encode('utf-8')
    return x

def construct_filename(subdir, filename):
    s = filename
    s = s.replace(' ', '-')
    s = s.replace('--', '-')
    s = s.replace('/', '_')
    return os.path.join(subdir, s)


class CallhomeManager(Manager):
    '''
    '''

    CALLHOME_PATH = defs.CALLHOME_PATH
    ssh_ip = None
    def __init__(self):
        super(CallhomeManager, self).__init__()
        self.debug_info_path = "%s/debug_info" % (self.CALLHOME_PATH)

    def _collect_debug_report(self, host):
        url = '/node/report'
        str_time = time.strftime("%Y%m%d%H%M%S")
        filename = '%s-%s.zip' % (host, str_time)
        filepath = os.path.join(self.CALLHOME_PATH, filename) 
        self.http_download(host=host, port=self.storagent_port, url=url, filepath=filepath)

    def write_file(self, filename, res):
        filename = construct_filename(self.CALLHOME_PATH, filename)
        with open(filename, 'w+') as f:
            f.write(res)

    def cmd_output(self, cmd):
        res = self._execute_remote(self.ssh_ip, cmd)
        self.write_file(cmd, res)
        return res
        
    def _collect_cluster_debug_info(self, cluster):
        self.ssh_ip = self._select_host(cluster_id=cluster.id)

        cmd = '%s list -v' % (self.lich.lich)
        self.cmd_output(cmd)


    def _clear_callhome_path(self):
        self.utils._exec_pipe("rm -rf %s/*" % (self.CALLHOME_PATH))

    def _zip_callhome_path_file(self):
        zip_name = "callhome-report.zip"
        cmd = "cd %s; zip -r %s ./*" % (self.CALLHOME_PATH, zip_name)
        self.utils._exec_pipe(cmd)
        return zip_name

    def send_mail_with_zip(self, zip_name):
        zip_filepath = os.path.join(self.CALLHOME_PATH, zip_name)
        attachments = [zip_filepath]

        subject ='Daily-report'
        alert_api.send_mail(subject, attachments=attachments, to_addrs=[defs.MAILSUPPORT_ADDRESS])


    def debug_info(self, error):
        '''

        redirect some custom error to callhome/debug-info file
        '''
        self.utils._exec_pipe("echo '%s'>> %s" % (error, self.debug_info_path))


    def callhome(self, cluster_id=1):
        cluster = models.Cluster.query.first()

        # if customer's callhome is not enabled, not send callhome mail
        customer = models.Customer.query.first()
        if (not customer) or (customer and not customer.callhome):
            return 'not enabled callhome'

        utils.make_dir(self.CALLHOME_PATH)
        self._clear_callhome_path()

        self.utils.exception_pass(self._collect_cluster_debug_info, cluster)

        hosts = cluster.hosts
        for host in hosts:
            try:
                self._collect_debug_report(host.ip)
            except Exception, e:
                self.debug_info("%s collect_debug_report error:%s" % (host.ip, e))
                pass

        zip_name = self._zip_callhome_path_file()

        self.send_mail_with_zip(zip_name)
        


if __name__ == '__main__':
    tgt = PoolManager()
    tgt.pool_sync(1)
